package key.dao.impl;

import key.dao.ProductDao;
import key.entity.Product;
import key.util.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class ProductDaoImpl implements ProductDao {

    @Override
    public long selectCountByTid(String tid) throws SQLException {

        QueryRunner queryRunner = new QueryRunner(DbUtils.getDataSource());

        String sql = "select count(1) from product where t_id = ?";

        Object result = queryRunner.query(sql, new ScalarHandler(), tid);

        Long total = (Long) result;
        return total;
    }

    @Override
    public List<Product> selectProductByPage(int page, int pageSize, String tid) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(DbUtils.getDataSource());

        String sql = "select p_id pid,t_id tid,p_name pname,p_time ptime ," +
                "p_image pimage,p_state pstate ,p_info pinfo ,p_price pprice " +
                "from product where t_id = ? limit ?,?;";

        List<Product> list = queryRunner.query(sql, new BeanListHandler<>(Product.class),
                tid, (page - 1) * pageSize, pageSize);

        return list;
    }

    @Override
    public Product selectProductByPid(String pid) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(DbUtils.getDataSource());

        String sql = "select p_id pid,t_id tid,p_name pname,p_time ptime ," +
                "p_image pimage,p_state pstate ,p_info pinfo ,p_price pprice " +
                "from product where p_id = ?;";

        Product product = queryRunner.query(sql, new BeanHandler<Product>(Product.class), pid);
        return product;
    }
}
